import React from 'react';
import { Button, Message, Field, Table, Balloon, Pagination } from '@teamix/ui';
import { ENUM } from 'utils/constants';
import { checkImportProjectName } from 'api/index.js';
import TableCellOverlay from 'components/importProjectListModal/overlay1';
import utils from 'utils';
import './index.scss';
import track from 'utils/track';
import intl from '../../../../locale';

const prefix = 'upgrade-step2';

const visiblityLevelObj = {
  0: intl.get({
    id: 'code-assets.containers.step2.PrivateVisibleOnlyToMembers',
    defaultMessage: '私有(仅代码库成员可见)',
  }),
  10: intl.get({
    id: 'code-assets.containers.step2.VisibleToEnterpriseAccessibleTo',
    defaultMessage: '企业可见(企业内成员可访问)',
  }),
};

export default class TbBuildResultTag extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
    };

    this.field = new Field(this);
  }

  componentDidMount() {
    track({
      action: 'into_step3',
    });

    this.getTableData();
  }

  // 解析名称
  getNewRepoName = (item) => {
    if (item.target_repo_path) {
      // 有导入后id，则需要去除第一级
      if (item.target_project_id) {
        return utils.getGroupPath(item.target_repo_path);
      } else {
        return item.target_repo_path;
      }
    } else {
      const oldName = item.original_repo_path;
      let text = '';
      if (oldName.includes('/')) {
        const arr = item.original_repo_path.split('/').map((t) => {
          return t.trim();
        });
        text = arr.join('/');
      } else {
        text = oldName;
      }
      return text || '';
    }
  };

  getTableData = () => {
    this.setState({
      isLoading: true,
    });

    const { allPageProjects, selectedKeys } = this.props;
    const list = allPageProjects.filter((item) => selectedKeys.includes(item.original_project_id));
    list.forEach((item) => {
      item.target_repo_path = this.getNewRepoName(item);
      // 没有公开性则设置为可以设置的值的第一个
      if (item.target_visibility_level === undefined) {
        item.target_visibility_level = item.original_visibility_level;
      }
    });
    this.setState({
      list,
    });

    this.checkAllPath(list);
  };

  checkSinglePath = (item) => {
    const name = this.getNewRepoName(item);

    return new Promise((resolve) => {
      const { organization } = window.FORCE;
      const namespace_id = organization.namespace_id || '';
      const visibility_level = item.target_visibility_level;
      checkImportProjectName({ path: name, name: '', namespace_id, visibility_level })
        .then(() => {
          resolve();
        })
        .catch((err) => {
          resolve({
            status: err.status,
            id: item.original_project_id,
            text: JSON.parse(err.responseText).cause || '',
          });
        });
    });
  };

  checkAllPath = (list) => {
    const allPromise = list.map((item) => {
      return this.checkSinglePath(item);
    });

    Promise.all(allPromise).then((res) => {
      const repeatList =
        res.filter((item) => {
          return item;
        }) || [];
      this.props.updateData({
        repeatList,
      });

      this.setState({
        isLoading: false,
      });
    });
  };

  goNext = () => {
    this.props.postProjects(this.state.list);
    this.props.updateData({
      selectedKeys: [],
    });
  };

  goPrev = () => {
    this.props.updateData({
      curStep: 1,
    });
  };

  saveName = (value, original_project_id) => {
    const { list } = this.state;
    const { repeatList } = this.props;
    const projectList = [...list];
    projectList.forEach((item) => {
      if (item.original_project_id === original_project_id) {
        item.target_repo_path = value;
      }
    });
    const index = repeatList.findIndex((item) => {
      return item.id === original_project_id;
    });
    if (index > -1) {
      repeatList.splice(index, 1);
    }
    this.setState({
      list: projectList,
    });

    this.props.updateData({
      repeatList: [...repeatList],
    });
  };

  renderOriginalVisibilityLevel = (value) => {
    return <div>{ENUM.visibility_level_text[value]}</div>;
  };

  renderImportRepoName = (value, index, record) => {
    const trigger = (
      <div className="table-cell-one-line import-repo-name-col" style={{ color: '#1B86EA' }}>
        <a href={record.original_web_url} target="_blank" rel="noreferrer">
          {value}
        </a>
      </div>
    );

    return (
      <Balloon.Tooltip trigger={trigger} align="t">
        {value}
      </Balloon.Tooltip>
    );
  };

  renderTargetVisibilityLevel = (value) => {
    return <div>{visiblityLevelObj[value]}</div>;
  };

  isInvalidRecord = (repeatList, original_project_id) => {
    return (
      repeatList.findIndex((item) => {
        return item.id === original_project_id;
      }) > -1
    );
  };

  // 所有数据均可编辑
  renderNewImportName = (value, index, record) => {
    const { repeatList } = this.props;
    const isRepeat = this.isInvalidRecord(repeatList, record.original_project_id);
    const invalidInfo = repeatList.find((item) => {
      return item.id === record.original_project_id;
    });
    return (
      <TableCellOverlay
        notAllowValidModify
        visibility_level={record.target_visibility_level}
        value={value}
        invalidInfo={invalidInfo}
        isRepeat={isRepeat}
        import_repo_id={record.original_project_id}
        saveName={this.saveName}
      />
    );
  };

  onPageChange = (value) => {
    const { step2Pagination } = this.props;
    this.props.updateData({
      step2Pagination: {
        ...step2Pagination,
        currentPage: value,
      },
    });
  };

  render() {
    const { isLoading, list } = this.state;
    const {
      selectedKeys,
      organizations,
      selectedOrganizationId,
      isUpgrading,
      step2Pagination,
      repeatList,
    } = this.props;
    const { pageSize, currentPage } = step2Pagination;
    const curOrganization =
      organizations.find((item) => item.organization_id === selectedOrganizationId) || {};
    // 前端分页
    const curList = list.slice((currentPage - 1) * pageSize, currentPage * pageSize);
    return (
      <div className={`${prefix}`}>
        <div className={`${prefix}-title`}>
          {intl.get(
            {
              id: 'code-assets.containers.step2.SelectedkeyslengthProjectsSelected',
              defaultMessage: '已选择 {selectedKeysLength} 个项目',
            },
            { selectedKeysLength: selectedKeys.length },
          )}
        </div>
        <div className={`${prefix}-desc`}>
          {intl.get({
            id: 'code-assets.containers.step2.UpgradeToEnterprise',
            defaultMessage: '升级至企业 「',
          })}
          {curOrganization.organization_name || ''}」
        </div>
        {repeatList.length ? (
          <div className={`${prefix}-message`}>
            <Message
              title={
                <div>
                  {intl.get(
                    {
                      id: 'code-assets.containers.step2.NumberOfConflictingQuestionsRepeatlistlength',
                      defaultMessage: '冲突问题数：{repeatListLength}',
                    },
                    { repeatListLength: repeatList.length },
                  )}
                </div>
              }
              type="error"
            />
          </div>
        ) : null}

        <div className={`${prefix}-table`}>
          <Table loading={isLoading} primaryKey="original_project_id" dataSource={curList}>
            <Table.Column
              title={intl.get({
                id: 'code-assets.containers.step2.Project',
                defaultMessage: '项目',
              })}
              dataIndex="original_repo_path"
              className="import-repo-name-col"
              cell={this.renderImportRepoName}
            />
            <Table.Column
              title={intl.get({
                id: 'code-assets.containers.step2.Openness',
                defaultMessage: '公开性',
              })}
              dataIndex="original_visibility_level"
              className="import-repo-visibility-col"
              cell={this.renderOriginalVisibilityLevel}
            />
            <Table.Column
              title={intl.get({
                id: 'code-assets.containers.step2.UpgradeHouKuName',
                defaultMessage: '升级后库名',
              })}
              dataIndex="target_repo_path"
              className="target-repo-name-col"
              cell={this.renderNewImportName}
            />
            <Table.Column
              title={intl.get({
                id: 'code-assets.containers.step2.PostUpgradePublicity',
                defaultMessage: '升级后公开性',
              })}
              dataIndex="target_visibility_level"
              className="target-repo-visibility-col"
              cell={this.renderTargetVisibilityLevel}
            />
          </Table>
        </div>
        <div className={`${prefix}-pagination`}>
          <Pagination
            onChange={this.onPageChange}
            current={currentPage}
            total={selectedKeys.length}
            showJump={false}
            pageSize={pageSize}
            pageSizeSelector={false}
            hideOnlyOnePage
          />
        </div>
        <div className={`${prefix}-line`} />
        <div>
          <Button type="normal" onClick={this.goPrev} style={{ marginRight: 12 }}>
            {intl.get({
              id: 'code-assets.containers.step2.PreviousStep',
              defaultMessage: '上一步',
            })}
          </Button>
          <Button
            type="primary"
            disabled={!!repeatList.length}
            loading={isUpgrading}
            onClick={this.goNext}
          >
            {intl.get({
              id: 'code-assets.containers.step2.StartUpgrade',
              defaultMessage: '开始升级',
            })}
          </Button>
        </div>
      </div>
    );
  }
}
